 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vng.survey.controller;


import com.vng.zing.survey.thrift.client.SurveyClient;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.Question;
import com.vng.zing.survey.thrift.model.QuestionStats;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import com.vng.zing.survey.thrift.model.SurveyStatsItem;
import com.vng.zing.survey.thrift.model.SurveyStatsResult;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.thrift.model.SurveyStatsPerDayItem;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vng.survey.model.CommonModel;
import vng.survey.model.RenderModel;


/**
 *
 * @author namhh
 */
public class StatisticController extends BaseController {

    @Override
    public String render(HttpServletRequest req, HttpServletResponse resp) throws IOException, Exception {
        boolean isChart = false;
        int idSurvey = Integer.parseInt(req.getParameter("id"));
        String[] value = new String[1];
        value[0] = String.format("%s", idSurvey);
//        String cached = (String) getCache(new String[]{String.format("%s", idSurvey)});
//        if (cached != null && !"".equals(cached)) {
//            return cached;
//        }
        String content = "";
        TemplateDataDictionary chart = TemplateDictionary.create();
        TemplateDataDictionary dic = TemplateDictionary.create();
        dic.setVariable("HEADER", CommonModel.getHeader(TemplateDictionary.create(), "Kết quả thống kê"));
        dic.setVariable("FOOTER", CommonModel.getFooter(TemplateDictionary.create()));

       

        SurveyClient surveyClient = SurveyClient.getInstance();
        SurveyItemResult itemResult = surveyClient.getSurvey(idSurvey);
        if (itemResult.getErro() != Error.SUCCESS || itemResult.getSurveyItem().getIDUser() != 1) {
            content = CommonModel.getError(dic, "Khảo sát không tồn tại!");
            return content;
        }
        if (itemResult.getSurveyItem().isOption() == false && 1 != 1) {
            return CommonModel.getError(dic, "Bạn không được phép xem trang này! ");
        }
        SurveyStatsResult statsResult = surveyClient.getSurveyStats(idSurvey);
        SurveyStatsItem statsItem = statsResult.getSurveyStatsItem();
        List<SurveyStatsPerDayItem> dayItems = surveyClient.getListStatsSurveyPerDay(idSurvey);
        List<String> day = new ArrayList<String>();
        List<Integer> view = new ArrayList<Integer>();
        List<Integer> response = new ArrayList<Integer>();
        for(SurveyStatsPerDayItem dayItem: dayItems){
            day.add(String.valueOf(dayItem.getDay()));
            view.add(dayItem.getView());
            response.add(dayItem.getResponse());
        }
         chart.setVariable("DATE", CommonModel.toJSON(day));
         chart.setVariable("VIEW", CommonModel.toJSON(view));
         chart.setVariable("RESPONSE", CommonModel.toJSON(response));
        

        dic.setVariable("TITLESURVEY", itemResult.getSurveyItem().getTitle());
        dic.setVariable("DECRIPTION", itemResult.getSurveyItem().getDescription());
        dic.setVariable("VIEW", String.valueOf(statsResult.getSurveyStatsItem().getView()));
        dic.setVariable("RESPONSE", String.valueOf(statsResult.getSurveyStatsItem().getResponse()));
        dic.setVariable("TIMESTART", CommonModel.getDate(itemResult.getSurveyItem().getBeginDay()));
        dic.setVariable("TIMEEND", CommonModel.getDate(itemResult.getSurveyItem().getEndDay()));
        dic.setVariable("RESPONSE_DETAIL_LINK", "detail?id=" + idSurvey);
        dic.setVariable("EDIT_LINK", "edit?id=" + idSurvey);
        Integer index = 1;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date date;
        isChart = true;
            dic.setVariable("ID_SURVEY", String.format("%s", idSurvey));

            for (Question question : itemResult.getSurveyItem().getQuestions()) {
                TemplateDataDictionary sliceQuestions = dic.addSection("SLICE_QUESTION");
                sliceQuestions.setVariable("INDEX", index.toString());
                //   sliceQuestions.setVariable("TYPE_ANSWER", String.format("%s",question.getType().getValue() ));

                if (question.getType() == QuesType.MULTI_CHOICE || question.getType() == QuesType.SINGLE_SELECTION) {

                    Map<Short, QuestionStats> map = statsItem.getStats();
                    QuestionStats questionStats = map.get(question.getIdQues());
                    if (questionStats == null) {
                        questionStats = new QuestionStats();
                        questionStats.setType(question.getType());
                        questionStats.setNumber(new ArrayList<Integer>());
                        for (String a : question.getChoices()) {
                            questionStats.getNumber().add(0);
                        }

                    }
                    // chart function       
                   
                    TemplateDataDictionary sliceChart = chart.addSection("SLICE_CHART");
                    List<String> choice = question.getChoices();
                    List<Integer> number = questionStats.getNumber();
                    sliceChart.setVariable("INDEX", String.valueOf(question.getIdQues()));
                    sliceChart.setVariable("TITLE", question.getTitleQues());
                    sliceChart.setVariable("CHOICE", CommonModel.toJSON(choice));
                    sliceChart.setVariable("NUMBER", CommonModel.toJSON(number));
                    if (question.getType() == QuesType.MULTI_CHOICE) {
                        sliceChart.setVariable("TYPE", "ColumnChart");
                    } else {
                        sliceChart.setVariable("TYPE", "PieChart");
                    }

                    TemplateDataDictionary chartAnswers = TemplateDictionary.create();
                    chartAnswers.setVariable("TYPE_ANSWER", String.format("%s", question.getType().getValue()));
                    chartAnswers.setVariable("INDEX", String.valueOf(question.getIdQues()));
                    content = CommonModel.getStatChart(chartAnswers);
                    sliceQuestions.setVariable("CHART", content);

                }
                if (question.getType() == QuesType.SINGLE_LINE || question.getType() == QuesType.MULTI_LINE) {
                    sliceQuestions.setVariable("ID_QUESTION", String.format("%s", question.getIdQues()));
                    sliceQuestions.setVariable("TITLE", question.getTitleQues());
                    TemplateDataDictionary dicAnswers = TemplateDictionary.create();
                    int page = (int) Math.floor(surveyClient.getCountResByQues(idSurvey, question.getIdQues()) / CommonModel.OFFSET);
                    List<AnswerItem> answerItems = surveyClient.getResByQues(idSurvey, question.getIdQues(), 0, CommonModel.OFFSET);
                    System.out.println("answerItems:" + answerItems);
                    if (answerItems.isEmpty()) {
                        dicAnswers.setVariable("CONTENT", "Chưa có câu trả lời nào!");
                        content = CommonModel.getEmpty(dicAnswers);
                    } else {
                        for (int i = 0; i < answerItems.size(); i++) {
                            TemplateDataDictionary sliceAnswer = dicAnswers.addSection("SLICE_ANSWER");
                            sliceAnswer.setVariable("NUMBER", String.format("%s", i + 1));
                            sliceAnswer.setVariable("USERNAME", answerItems.get(i).getDisplayName());
                            sliceAnswer.setVariable("CONTENT", answerItems.get(i).getAnswer());

                            date = new Date(((long) answerItems.get(i).getTimeResponse()) * 1000L);
                            sliceAnswer.setVariable("TIMERESPONSE", df.format(date));

                        }

                        if (question.getType() == QuesType.SINGLE_LINE) {
                            content = CommonModel.getStatTable(dicAnswers);
                        } else {
                            content = CommonModel.getStatMutilLine(dicAnswers);
                        }

                        if (page > 1) {
                            TemplateDataDictionary dicPage = TemplateDictionary.create();
                            dicPage.setVariable("COUNT", String.format("%s", page));
                            dicPage.setVariable("OFFSET", String.format("%s", CommonModel.OFFSET));
                            dicPage.setVariable("NAME", "paging_stat");
                            String paging = CommonModel.getPaging(dicPage);
                            sliceQuestions.setVariable("PAGE", paging);
                        }
                    }

                    sliceQuestions.setVariable("TABLE", content);

                }
                index++;
            }
            if (isChart) {
                content = CommonModel.getChartFunciton(chart);
                dic.setVariable("CHARTFUCTION", content);
            }

            Template template = RenderModel.getCTemplate("statistic");
            content = template.renderToString(dic);
      
        setCache(new String[]{String.format("%s", idSurvey)}, 3600, content);
        return content;
    }
}
